package com.jungle.bfi.service.metadata.impl;

import com.jungle.base.dao.SpecBuilder;
import com.jungle.base.domain.bo.BaseUserBo;
import com.jungle.base.service.AbstractService;
import com.jungle.bfi.domain.bo.ApiUrlBo;
import com.jungle.bfi.entity.ApiUrlPo;
import com.jungle.bfi.service.metadata.ApiUrlService;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.List;

@Service(value = "apiUrlService")
public class ApiUrlServiceImpl extends AbstractService<ApiUrlPo, ApiUrlBo, String> implements ApiUrlService {

    @Override
    protected String getBoId(ApiUrlBo bo) {
        // 基本操作条件 + 自定义查询条件
        Specification<ApiUrlPo> spec = new SpecBuilder<ApiUrlPo>(bo).and(extSpec(bo)).toSpec();
        List<ApiUrlPo> list = this.repository.findAll(spec);
        if (!list.isEmpty()) {
            ApiUrlPo apiUrlPo = list.get(0);
            bo.setId(apiUrlPo.getId());
        }
        return bo.getId();
    }

    private Specification<ApiUrlPo> extSpec(ApiUrlBo bo) {
        if (bo == null) {
            return null;
        }
        return ((root, query, cb) -> {
            if (StringUtils.isBlank(bo.getApiName()) && StringUtils.isBlank(bo.getType())) {
                return null;
            } else if (StringUtils.isNotBlank(bo.getApiName())) {
                return cb.equal(root.get("apiName"), bo.getApiName());
            } else if (StringUtils.isNotBlank(bo.getType())) {
                return cb.equal(root.get("type"), bo.getType());
            } else {
                return cb.and(cb.equal(root.get("type"), bo.getType()), cb.equal(root.get("apiName"), bo.getApiName()));
            }
        });
    }

    @Override
    protected String newPoId() {
        return Sid.nextShort();
    }

    @Override
    protected ApiUrlPo createPo(ApiUrlBo bo, BaseUserBo userBo) {
        return mapper.map(bo, ApiUrlPo.class);
    }

}
